package com.jewelry.crm.controller;


import com.jewelry.crm.model.domain.Supplier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.Collection;
import static com.jewelry.crm.model.bo.SupplierBo.*;
import static com.jewelry.crm.common.Common.logger;

@Controller
@RequestMapping("/suppliers")
public class SupplierController {

    @RequestMapping(value="/list", method = RequestMethod.GET)
    public ModelAndView list() throws Throwable{
        Collection suppliers = getAllSuppliers();
        logger.info("Going to show the list");
        return new ModelAndView("suppliers/suppliersList", "suppliers", suppliers);
    }

    @RequestMapping(value="/show/{id}", method = RequestMethod.GET)
    public ModelAndView show(@PathVariable(value="id") int id) throws Throwable{
        Supplier supplier = getSupplierById(id);
        return new ModelAndView("suppliers/supplierShow", "supplier", supplier);
    }

    @RequestMapping(value="/delete/{id}", method = RequestMethod.GET)
    public ModelAndView delete(@PathVariable(value="id") int id) throws Throwable{
        deleteSupplier(getSupplierById(id));
        return new ModelAndView( "redirect:/suppliers/list.html" );
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView addSuppliers( @ModelAttribute("supplier") Supplier supplier) {
        return new ModelAndView ("suppliers/supplierAdd");
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView saveSupplier ( @ModelAttribute("supplier") Supplier supplier) throws Throwable {
        addSupplier(supplier);
        return new ModelAndView ( "redirect:/suppliers/list.html" );
    }

    @RequestMapping(value="/edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable(value="id") int id) throws Throwable{
        Supplier supplier = getSupplierById(id);
        return new ModelAndView("suppliers/supplierEdit", "supplier", supplier);
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    public ModelAndView updateSuppliers (@PathVariable(value="id") int id, @ModelAttribute("supplier") Supplier supplier) throws Throwable {

        Supplier oldSupplier = getSupplierById(id);
        oldSupplier.setName(supplier.getName());
        oldSupplier.setContact(supplier.getContact());
        oldSupplier.setDescription(supplier.getDescription());
        oldSupplier.setEmail(supplier.getEmail());
        updateSupplier(oldSupplier);
        return new ModelAndView ( "redirect:/suppliers/show/" + id +".html" );
    }

}
